package nth.randcats.server;

import nth.randcats.client.VerifyCredentials;

import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import com.gargoylesoftware.htmlunit.ScriptException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class VerifyCredentialsImpl extends RemoteServiceServlet implements VerifyCredentials {

	@Override
	public boolean isValid(String email, String password) {
		HtmlUnitDriver driver = new HtmlUnitDriver(false);

		driver.get("http://www.facebook.com");

		if (driver.getTitle().equals("Facebook")) { // already logged in
			driver.findElement(By.id("navAccountLink")).click();
			driver.findElementByCssSelector(".logoutButton").findElement(By.tagName("input")).click();
			assert !driver.getTitle().equals("Facebook") : "Tried to log out but failed";
		}

		System.out.println(driver.getTitle());
		final WebElement emailInput = driver.findElement(By.id("email"));
		final WebElement passInput = driver.findElement(By.id("pass"));

		emailInput.sendKeys(email);
		passInput.sendKeys(password);

		emailInput.submit();
		final boolean result = driver.getTitle().equals("Facebook");

		driver.manage().deleteAllCookies();
		driver.quit();

		return result;
	}

}
